<template>
  <view>
    <tn-custom :is-alpha="true">
      <block slot="left">
        <view class='action border-custom text-white bp-top-home' :style="'width:' + Custom.width + 'px;margin-left:calc(750rpx - ' + Custom.right + 'px)'"
          @click="goBack">
          <text class='cuIcon-back'></text>
          <text class='cuIcon-homefill'></text>
        </view>
      </block>
    </tn-custom>

    <swiper class="screen-swiper square-dot" :indicator-dots="true" :circular="true" :autoplay="true" interval="5000"
      duration="500" style="margin-top:-64px">
      <swiper-item v-for="(main_image_item,main_image_index) in productData.main_image['prefix']" :key="main_image_index" @click="prevMainImage(main_image_index)">
        <image :src="main_image_item" mode="aspectFill"></image>
        <!-- <video :src="item.url" autoplay loop muted :show-play-btn="false" :controls="false" objectFit="cover" v-if="item.type=='video'"></video> -->
      </swiper-item>
    </swiper>

    <view class="cu-bar">
      <view class="action">
        <text class="text-black text-bold margin-top-sm tn-align text-lg">{{ productData.title }}</text>
      </view>
    </view>
    <view class="cu-bar solid-bottom">
      <view class='action'>
        <text class='text-red product-price text-bold text-xxl margin-bottom-sm'>￥</text>
        <text class='text-red  text-bold'>{{ productData.price.min + '-' + productData.price.max}}</text>
      </view>
      <view class='action'>
        <text class="text-gray">销量 {{ productData.virtual_sales_volume > productData.sales_volume ? productData.virtual_sales_volume : productData.sales_volume }}</text>
      </view>
    </view>

    <view class="cu-list menu tn-border">
      <!-- <view class="cu-item">
        <view class="content">
          <text class="">产品标签</text>
        </view>
        <view class="action">
          <view class="cu-tag round bg-orange light">音乐</view>
          <view class="cu-tag round bg-olive light">电影</view>
          <view class="cu-tag round bg-blue light">旅行</view>
        </view>
      </view>
      <view class="cu-item">
        <view class="content">
          <text class="">优惠减免</text>
        </view>
        <view class="action">
          <button class="cu-btn round bg-orange shadow sm">
            <text class="cuIcon-redpacket_fill padding-right-xs"></text> 领取</button>
        </view>
      </view>
      <view class="cu-item">
        <view class="content">
          <text class="">他们都在买</text>
        </view>
        <view class="action">
          <view class="cu-avatar-group" style="margin-right: -10rpx;">
            <view class="cu-avatar round sm" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big10001.jpg);"></view>
            <view class="cu-avatar round sm" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big81005.jpg);"></view>
            <view class="cu-avatar round sm" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big25002.jpg);"></view>
            <view class="cu-avatar round sm" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big91012.jpg);"></view>
          </view>
        </view>
      </view> -->
      <view v-if="productData.single_sku == 0" class="cu-item arrow" @click="openProductSpecsModal(1)">
        <view class="content">
          <text class="">规格</text>
        </view>
        <view class="action  text-right">
          <view class="name-title-a">请选择商品规格</view>
        </view>
      </view>
      <view v-if="productData.parameters.length > 0" class="cu-item arrow" @click="openProductParametersModal">
        <view class="content">
          <text class="">参数</text>
        </view>
        <view class="action text-right">
          <view class="name-title-a">查看商品参数</view>
        </view>
      </view>
    </view>


    <view class="tn-border product-detail-title">
      <view>
        商品详情
      </view>
    </view>


    <view class="margin text-lg" style="margin-bottom: 100rpx;">
      <u-parse :content="productData.content" :imageProp="{lazyLoad: true}" @navigate="parseNavigate" />
    </view>


    <view class="cu-modal bottom-modal" :class="showProductParameters?'show':''" @click="closeProductParametersModal">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">产品参数</view>
          <view class="action" @tap.native.stop="closeProductParametersModal">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="cu-list menu tn-border">
          <view class="cu-item" v-for="(parameters_item, parameters_index) in productData.parameters" :key="parameters_index">
            <view class="content">
              <text class="fl">{{ parameters_item.name }}</text>
            </view>
            <view class="action">
              <view class="">{{ parameters_item.value }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <goods-sku-popup
      v-model="showProductSpecs"
      :custom-action="getProductSkuData"
      :border-radius="20"
      :mode="productSpecsButtonMode"
      buy-now-color = "#ffffff"
      buy-now-background-color="#e54d42"
      add-cart-color = "#ffffff"
      add-cart-background-color="#f37b1d"
      goods-id-name="id"
      sku-id-name="specs_id"
      goods-thumb-name="product_thumb"
      sku-list-name="specs_list"
      spec-list-name="property_list"
      sku-name="property_name"
      sku-arr-name="property_name_arr"
      @close="closeProductSpecsModal"
      @add-cart="addProductToCart"
      @buy-now="buyProductToNow"
    ></goods-sku-popup>
    
    <view class="cu-tabbar-height"></view>
    
    <view class="cu-bar bg-white tabbar border shop tn-footerfixed" :class="[showProductSpecs ? 'tn-cu-bar-hide' : '']">
      <button class="action text-gray" open-type="contact">
        <view class="cuIcon-service">
        </view> 客服
      </button>
      <view class="action text-gray" @click="navShoppingCart">
        <view class="cuIcon-cart">
          <!-- <view class="cu-tag badge light" style="background-color: #06B8FF;">99</view> -->
        </view>
        购物车
      </view>
      <view class="btn-group">
        <button class="cu-btn bg-orange round shadow-blur" :disabled="productData.virtual_product === 1" @click="bottomAddProductToCart">加入购物车</button>
        <button class="cu-btn bg-red round shadow-blur" @click="bottomBugProductToNow">立即购买</button>
      </view>
    </view>
    
    <tn-wx-login :show="showLogin" desc="用户记录您的登录信息" @closeLoginModal="closeLoginModal" @getUserInfo="getUserInfo"></tn-wx-login>

  </view>
</template>

<script>
  import uParse from '../components/feng-parse/parse'
  import GoodsSkuPopup from '@/tn_shop/components/vk-u-goods-sku-popup/vk-u-goods-sku-popup.vue'
  import { checkUserScope, getUserInfo } from '@/utils/user.js'
  import { addProductToShoppingCart, addSubmitOrderProductToCache } from '@/utils/shop.js'
  import { getProductDetailByID, getProductSpecsData } from '@/api/tn-shop.js'
  
  const util = require('@/utils/util')
  var that;											// 当前页面对象
  export default {
    name: 'TnShopProductDetail',
    components: { uParse, GoodsSkuPopup },
    data() {
      return {
        Custom: this.Custom,
        CustomBar: this.CustomBar,
        from: '',
        id:0, // 商品id
        productData: {
          main_image: {
            prefix: []
          },
          price: {
            min: 0,
            max: 0
          },
          virtual_product: 0,
          sales_volume: 0,
          parameters: [],
          sku_data: {},
          single_sku: 0
        },  // 商品的详细信息
        showProductParameters: false, // 是否显示商品参数
        showProductSpecs: false,  // 是否显示商品规格数据
        productSpecsButtonMode: 1, // 商品选择规格弹窗按钮模式
        checkUserScopeFlag: false, //用户是否已经授权
        showLogin: false, //打开登陆框
      };
    },
    onLoad(options) {
      if (!options.id) {
        uni.showModal({
          title: '参数错误',
          content: '请求商品数据错误',
          showCancel: false,
          success: () => {
            uni.navigateBack({
              delta: 1
            })
          }
        })
        return
      }
      
      that = this
      this.id = options.id
      this.from = options.from || ''
      this._loadData()
    },
    onPullDownRefresh() {
      this.productData = {}
      this._getProductData()
    },
    methods: {
      
      // 获取商品的sku数据，这里每一次选择规格的时候都会取请求一次服务器获取规格数据，这样可以保证库存是最新的
      getProductSkuData() {
        return new Promise((resolve) => {
          resolve(that.productData.sku_data)
        })
      },
      
      // 添加商品到购物车
      addProductToCart(selectShop) {
        // 检查用户是否已经登录
        this._checkUserScope().then(() => {
          // console.log(selectShop);
          if(addProductToShoppingCart(selectShop)) {
            uni.showToast({
              icon: 'none',
              title: '添加商品成功'
            })
            this.closeProductSpecsModal()
          }
        }).catch((err) => {
          console.log(err);
          this.showLogin = true
        })
      },
      
      // 立即购买商品
      buyProductToNow(selectShop) {
        // 检查用户是否已经登录
        this._checkUserScope().then(() => {
          console.log(selectShop);
          addSubmitOrderProductToCache([{
            id: selectShop.specs_id,
            product_id: selectShop.product_id,
            virtual_product: selectShop.virtual_product,
            title: selectShop.product_title,
            property: selectShop.property_name_arr,
            image: selectShop.image,
            price: selectShop.selling_price,
            stock: selectShop.stock,
            count: selectShop.buy_num
          }])
          uni.navigateTo({
            url: '/tn_shop/submit_order/submit_order?from=product'
          })
        }).catch(() => {
          this.showLogin = true
        })
      },
      
      // 底部添加到购物车按钮
      bottomAddProductToCart() {
        if (this.productData.single_sku == 1) {
          this.addProductToCart(Object.assign({...this.productData.sku_data['specs_list']}, {buy_num: 1}))
        } else {
          this.openProductSpecsModal(2)
        }
      },
      
      // 底部立即购买商品按钮
      bottomBugProductToNow() {
        if (this.productData.single_sku == 1) {
          this.buyProductToNow(Object.assign({...this.productData.sku_data['specs_list']}, {buy_num: 1}))
        } else {
          this.openProductSpecsModal(3)
        }
      },
      
      // 打开主图进行预览
      prevMainImage(index) {
        uni.previewImage({
          current: index,
          urls: this.productData['main_image']['prefix']
        })
      },
      
      //获取用户登陆状态
      getUserInfo() {
        if (res != null) {
          updateUserInfoToServer(res).then(() => {
            this.checkUserScopeFlag = true;
            util.showTips('登陆成功', '请继续执行上一步操作');
            this.closeLoginModal()
          }).catch(() => {
            util.showTips('授权提示', '获取授权失败')
            this.closeLoginModal()
          })
        } else {
          this.closeLoginModal()
        }
      },
      
      // 打开和关闭商品规格选择数据窗口
      openProductSpecsModal(mode) {
        // 判断是否为服务商品，如果是则禁止加入购物车
        if (this.productData.virtual_product == 1) {
          this.productSpecsButtonMode = 3
        } else {
          this.productSpecsButtonMode = mode
        }
        uni.showLoading()
        getProductSpecsData(this.id).then((response) => {
          uni.hideLoading()
          this.productData.sku_data = response.data
          this.showProductSpecs = true
        }).catch((err) => {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '获取数据失败'
          })
        })
      },
      closeProductSpecsModal() {
        this.showProductSpecs = false
      },
      
      // 打开和关闭商品参数数据窗口
      openProductParametersModal() {
        this.showProductParameters = true
      },
      closeProductParametersModal() {
        this.showProductParameters = false
      },
      
      // 判断是跳转到首页还是上一页
      goBack() {
        if (this.from == 'share') {
          uni.navigateTo({
            url: '/pages/index/index'
          })
        } else {
          uni.navigateBack({
            delta: 1
          })
        }
      },
      
      // 跳转到购物车
      navShoppingCart() {
        uni.navigateTo({
          url: '/tn_shop/shopping_cart/shopping_cart'
        })
      },
      
      // 关闭登录窗口
      closeLoginModal() {
        this.showLogin = false
      },
      
      // 处理富文本的链接点击
      parseNavigate(href) {
        uni.setClipboardData({
          data: href,
          complete: () => {
            uni.showToast({
              title: '复制链接成功'
            })
          }
        })
      },
      
      // 加载数据
      _loadData() {
        this._getProductData()
        this._checkUserScope()
      },
      
      // 获取商品数据
      _getProductData() {
        uni.showLoading({
          title: '加载中'
        })
        getProductDetailByID(this.id).then((res) => {
          uni.hideLoading()
          uni.stopPullDownRefresh()
          // console.log(res)
          this.productData = res.data
        }).catch((err) => {
          uni.hideLoading()
          uni.stopPullDownRefresh()
          uni.showToast({
            icon: 'none',
            title: '获取数据失败',
            success: () => {
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            }
          })
        })
      },
      
      // 检查当前用户的权限
      _checkUserScope() {
        return new Promise((resolve, reject) => {
          checkUserScope().then((res) => {
            this.checkUserScopeFlag = res
            resolve();
          }).catch((res) => {
            this.checkUserScopeFlag = res
            reject();
          });
        });
      }
    }

  }
</script>

<style lang="scss" scoped>
  .screen-swiper {
    min-height: 750rpx;
  }

  .product-price {
    margin-left: -5rpx;
  }

  .margin-bottom-sm {
    margin-bottom: 12rpx;
  }

  .product-detail-imgs image {
    width: 100%;
    float: left;
    /* height:400rpx; 不定高了*/
    border: 0;
    padding: 0;
    margin: 0
  }
  
  .product-detail-title {
    width: 100%;
    height: 36px;
    line-height: 36px;
    text-align:center;
    position:relative;
  }
  .product-detail-title view::before, .product-detail-title view::after {
    position:absolute;
    background:#ccc;
    content:"";
    height:1px;
    top:65%;
    width:155px;
  }
  .product-detail-title view::before {
    left: 10px;
  }
  .product-detail-title view::after {
    right: 10px;
  }
</style>
